angular.module('scanPrint.services')

.factory('InitService', ['$q', '$ionicPlatform', '$ionicHistory', '$timeout', '$cordovaToast', '$rootScope',
	function($q, $ionicPlatform, $ionicHistory, $timeout, $cordovaToast, $rootScope) {
	    var defer = $q.defer();

		init();

		return defer.promise;

		function init () {
			$ionicPlatform.registerBackButtonAction(
				onHardwareBackButton,
				110
			);

            document.addEventListener('rfiduhf.DataReceived', function (e) {
                $rootScope.$broadcast('rfiduhf.DataReceived', e.rfidUhfData);
            }, false);
            document.addEventListener('bluetoothprint.DataReceived', function (e) {
                $rootScope.$broadcast('bluetoothprint.DataReceived', e.bluetoothPrintData);
            }, false);
            document.addEventListener('bluetoothprint.StatusReceived', function (e) {
                $rootScope.$broadcast('bluetoothprint.StatusReceived', e.bluetoothPrintStatus);
            }, false);
			defer.resolve();
		}

		var _confirmExit = false;
		function onHardwareBackButton(e) {
			if ($ionicHistory.backView()) {
			 	$ionicHistory.goBack();
			} else {
				if (_confirmExit) {
					ionic.Platform.exitApp();
				} else {
					_confirmExit = true;
					$cordovaToast.showShortBottom('再按一次退出');
					$timeout(function () {
					 	_confirmExit = false;
					}, 2000);
				}
			}

			e.preventDefault();
			return false;
		} 
	}
]);
